package com.suzhe.ymall.product.controller;

import com.suzhe.ymall.common.annotation.LoginAuth;
import com.suzhe.ymall.common.pojo.ApiResEntity;
import com.suzhe.ymall.product.param.LockStockParam;
import com.suzhe.ymall.product.pojo.Sku;
import com.suzhe.ymall.product.service.IProductService;
import com.suzhe.ymall.product.service.ISkuService;
import com.suzhe.ymall.product.service.ISpuDetailService;
import com.suzhe.ymall.product.service.ISpuService;
import com.suzhe.ymall.product.vo.SkuVo;
import com.suzhe.ymall.product.vo.SpuVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("product")
@Slf4j
public class ProductController {

    @Autowired
    ISkuService iSkuService;

    @Autowired
    ISpuService iSpuService;

    @Autowired
    ISpuDetailService iSpuDetailService;

    @Autowired
    IProductService iProductService;

    @GetMapping("/querySkuVosByIds")
    public List<SkuVo> querySkuVosByIds(@RequestParam("ids") List<Long> ids) {
        List<Sku> skus = (List)iSkuService.listByIds(ids);
        List<Integer> spuIds = skus.stream().map(Sku::getSpuId).collect(Collectors.toList());
        Map<Integer, String> spuTitleMap = iSpuService.listByIds(spuIds).stream()//
                .collect(Collectors.toMap(spu -> spu.getId(), spu -> spu.getTitle()));
        List<SkuVo> skuVos = new ArrayList<>(skus.size());
        for (Sku sku: skus) {
            SkuVo skuVo = new SkuVo();
            skuVo.setId(sku.getId());
            skuVo.setPrice(sku.getPrice());
            skuVo.setDesc(sku.getTitle());
            skuVo.setTitle(spuTitleMap.get(sku.getSpuId()));
            skuVo.setStock(sku.getStock());
            skuVo.setImgUrl(sku.getImgUrl());
            skuVos.add(skuVo);
        }
        return skuVos;
    }

    @PostMapping("/lockStock")
    @LoginAuth
    public ApiResEntity lockStock(@RequestBody LockStockParam lockStockParam) {

        return iSkuService.lockStock(lockStockParam);
    }

    @GetMapping("/getProductDetail")
    @ApiOperation(value="获取商品详细")
    public ApiResEntity getProductDetail(Integer id){
        SpuVo spuVo = iProductService.getProductDetial(id);
        return ApiResEntity.ok(spuVo);
    }

}
